package reverseKGroup

type ListNode struct {
	Val  int
	Next *ListNode
}

func ReverKGroup(head *ListNode, k int) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}
	dummy := &ListNode{}
	dummy.Next = head
	pre := dummy
	end := dummy
	for end.Next != nil {
		for i := 0; i < k && end != nil; i++ {
			end = end.Next
		}
		if end == nil {
			break
		}
		next := end.Next
		end.Next = nil
		start := pre.Next
		pre.Next = Reverse(start)
		start.Next = next
		pre = start
		end = start

	}
	return dummy.Next

	return nil
}

func Reverse(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}

	preNode := &ListNode{}

	curNode := head

	nextNode := &ListNode{}
	for curNode != nil {
		nextNode = curNode.Next
		curNode.Next = preNode
		preNode = curNode
		curNode = nextNode
	}

	return preNode
}
